package payrechargelogic

import (
	"context"
	"math"

	model "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/recharge"
	withdrawModel "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/withdraw"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/pkg/xerrors"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RechargeChannelListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRechargeChannelListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RechargeChannelListLogic {
	return &RechargeChannelListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RechargeChannelListLogic) RechargeChannelList(in *rpc.RechargeChannelListRequest) (*rpc.RechargeChannelListResponse, error) {
	var commonResp rpc.CommonResp

	filter := map[string]interface{}{}
	if in.Type != 0 {
		filter["type"] = in.Type
	}
	if in.Name != "" {
		filter["name"] = in.Name
	}
	if in.Status != 0 {
		filter["status"] = in.Status
	}

	channels, total, err := model.NewRechargeChannelModel(l.ctx, l.svcCtx.Db).GetAllRechargeChannels(filter, in.Page, in.PageSize)
	if err != nil {
		commonResp.Code = xerrors.DBError
		commonResp.Message = "Database operation error"
		return &rpc.RechargeChannelListResponse{CommonResp: &commonResp}, err
	}

	var rpcChannels []*rpc.RechargeChannel
	for _, ch := range channels {
		toRate := withdrawModel.NewVirtualDicModel(l.ctx, l.svcCtx).GetRate(ch.Coin)

		rpcChannels = append(rpcChannels, &rpc.RechargeChannel{
			Id:           ch.ID,
			MappingCode:  ch.MappingCode,
			Type:         ch.Type,
			Name:         ch.Name,
			Level:        ch.Level,
			UserGroup:    ch.UserGroup,
			BonusRate:    ch.BonusRate,
			MinAmount:    ch.MinAmount,
			MaxAmount:    ch.MaxAmount,
			AmountConfig: ch.AmountConfig,
			MerchantId:   ch.MerchantID,
			AppId:        ch.AppId,
			AppCode:      ch.AppCode,
			SecretKey:    ch.SecretKey,
			Url:          ch.URL,
			ReturnUrl:    ch.ReturnUrl,
			NotifyUrl:    ch.NotifyUrl,
			PubKey:       ch.PubKey,
			PrivateKey:   ch.PrivateKey,
			StartTime:    ch.StartTime,
			EndTime:      ch.EndTime,
			Sort:         ch.Sort,
			Status:       ch.Status,
			IsTestable:   ch.IsTestable,
			WhiteList:    ch.WhiteList,
			Remark:       ch.Remark,
			Icon:         ch.Icon,
			ChannelName:  ch.ChannelName,
			Inr:          ch.Coin,
			ToRate:       toRate,
		})
	}
	// Calculate total pages
	totalPages := int64(math.Ceil(float64(total) / float64(in.PageSize)))
	pagination := rpc.Pagination{
		PageSize:  in.PageSize,
		Page:      in.Page,
		Total:     total,
		TotalPage: totalPages,
	}
	return &rpc.RechargeChannelListResponse{
		Records:    rpcChannels,
		Pagination: &pagination,
		CommonResp: &commonResp,
	}, nil
}
